import { loginAPI, getUserInfoAPI, logoutAPI } from '@/api/index.js'
import { setToken, getToken, removeToken } from '@/utils/userToken.js'
export default {
  // 开启命名空间
  namespaced: true,

  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    POSTLOGIN(state, data) {
      state.token = data
    },
    GETUSERINFO(state, data) {
      state.userInfo = data
    },
    DELETEUSERINFO(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    }
  },
  actions: {
    // 登录
    async postLogin({ dispatch, commit }, data) {
      const { token } = await loginAPI(data)
      commit('POSTLOGIN', token)
      setToken(token)
      dispatch('getUserInfo')
    },
    // 获取用户信息
    async getUserInfo({ commit }) {
      const data = await getUserInfoAPI()
      commit('GETUSERINFO', data)
    },
    // 退出登录
    async logout({ commit }) {
      await logoutAPI()
      commit('DELETEUSERINFO')
    }
  },
}
